package org.hy.pay.message.exception;



import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hy.pay.common.core.exception.BizException;
import org.hy.pay.message.model.AjaxJson;
import org.hy.pay.message.util.JSONHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;


/**
 * spring mvc 全局处理异常捕获 根据请求区分ajax和普通请求，分别进行响应.
 * 第一、异常信息输出到日志中。
 * 第二、截取异常详细信息的前50个字符，写入日志表中t_s_log。
 */
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver {
//	@Autowired
//	private SystemService systemService;
	//记录日志信息
	private static final Logger log = Logger
			.getLogger(GlobalExceptionResolver.class);
	//记录数据库最大字符长度
	private static final int WIRTE_DB_MAX_LENGTH = 1500;
	//记录数据库最大字符长度
	private static final short LOG_LEVEL = 6;
	//记录数据库最大字符长度
	private static final short LOG_OPT = 3;
	/**
	 * 对异常信息进行统一处理，区分异步和同步请求，分别处理
	 */
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
     
          return processException(request, response, handler, ex);
	}

	/**
	 * 获取最原始的异常出处，即最初抛出异常的地方
	 */
    private Throwable deepestException(Throwable e){
        Throwable tmp = e;
        int breakPoint = 0;
        while(tmp.getCause()!=null){
            if(tmp.equals(tmp.getCause())){
                break;
            }
            tmp=tmp.getCause();
            breakPoint++;
            if(breakPoint>1000){
                break;
            }
        } 
        return tmp;
    }
	/**
	 * 处理异常.
	 * @param request
	 * @param response
	 * @param handler
	 * @param deepestException
	 * @param isajax
	 * @return
	 */
	private ModelAndView processException(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			 Exception ex) {
		 Throwable deepestException = deepestException(ex);
		//步骤一、异常信息记录到日志文件中.
		  log.error("全局处理异常捕获:",deepestException);
		//步骤二、异常信息记录截取前50字符写入数据库中.
	   //	logDb(ex);
		//步骤三、分普通请求和ajax请求分别处理.
		  
/*			if(ex instanceof CustomException ){
				CustomException tokenExcepiton = (CustomException)ex;
				if(tokenExcepiton.getErrorCode().equals(CommonConstant.User.USER_NOT_LOGGIN.getCode()) ){
					
					return processNotAjax( request, response,  handler,  ex);			
					
				}else{
					return processAjax(request,response,handler,ex);
				}
			}else{*/
				return processAjax(request,response,handler,ex);
	  //	  }
	}
	/**
	 * 异常信息记录截取前50字符写入数据库中
	 * @param ex
	 */
	/*private void logDb(Throwable ex) {
		//String exceptionMessage = getThrowableMessage(ex);
		String exceptionMessage = "错误异常: "+ex.getClass().getSimpleName()+",错误描述："+ex.getMessage();
		if(oConvertUtils.isNotEmpty(exceptionMessage)){
			if(exceptionMessage.length() > WIRTE_DB_MAX_LENGTH){
				exceptionMessage = exceptionMessage.substring(0,WIRTE_DB_MAX_LENGTH);
			}
		}
		systemService.addLog(exceptionMessage, LOG_LEVEL, LOG_OPT);
	}*/
	
	
	/**
	 * 普通页面异常处理并返回.
	 * @param request
	 * @param response
	 * @param handler
	 * @param deepestException
	 * @return
	 */
	private ModelAndView processNotAjax(HttpServletRequest request,
			HttpServletResponse response, Object handler, Throwable ex) {
		String exceptionMessage = getThrowableMessage(ex);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("exceptionMessage", exceptionMessage);
		model.put("ex", ex);
		return new ModelAndView(new RedirectView("login/modeltest"));

	}
	
	
	/**
	 * ajax异常处理并返回.
	 * @param request
	 * @param response
	 * @param handler
	 * @param deepestException
	 * @return
	 */
	private ModelAndView processAjax(HttpServletRequest request,
			HttpServletResponse response, Object handler,Exception ex){
		ModelAndView empty = new ModelAndView();	          
		response.setHeader("Cache-Control", "no-store");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
	//	AjaxJson json = new AjaxJson();
		PrintWriter pw = null;
		AjaxJson json = null;
		try {
			if(ex instanceof MessageBizException ){
				MessageBizException exception = (MessageBizException)ex;
				//	json.setResCode(tokenExcepiton.getErrorCode());
				//	json.setResMsg(tokenExcepiton.getErrorMsg());
				  json =  AjaxJson.error(exception.getCode(), exception.getMsg());
				
			}else if(ex instanceof BizException){
				BizException businessException = (BizException)ex;
				//   json.setResCode(businessException.getErrorCode());
				//	json.setResMsg(businessException.getErrorMsg());
				  json =  AjaxJson.error(businessException.getCode(), businessException.getMsg());
			}else{
				//json.setResCode(CommonConstant.EXCEPTION_UNKNOWN_ERROR);
				//json.setResMsg(CommonConstant.EXCEPTION_UNKNOWN_ERROR_STR);
				//  json.error(exception.getCode(), exception.getMsg());
				json =  AjaxJson.error(MessageBizException.UNKNOW_EXCEPTION, "未知错误");
			}
			pw=response.getWriter();
			pw.write(JSONHelper.bean2json(json));
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			pw.close();
		}
		empty.clear();
		return empty;
	}
	
	/**
	 * 返回错误信息字符串
	 * 
	 * @param ex
	 *            Exception
	 * @return 错误信息字符串
	 */
	public String getThrowableMessage(Throwable ex) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		ex.printStackTrace(pw);
		return sw.toString();
	}
}
